//
//  MHCHChoisTimeView.m
//  Go!
//
//  Created by rimi on 16/7/13.
//  Copyright © 2016年 MHCH. All rights reserved.
//

#import "MHCHChoisTimeView.h"
#import "CalendarCollectionViewCell.h"

@interface MHCHChoisTimeView()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, retain) NSDate *date; /**< 给定的date */
@property (nonatomic, strong) UIView *calendarView;  /**< 日历视图 */
@property (nonatomic, strong) UILabel_Font *promptChoisTimeLable;  /**< 头部提示 */
@property (nonatomic, retain) UICollectionView *collectionView;  /**< 集合视图 */
@property (nonatomic, strong) UIButton *nextMouthBtn;  /**< 下一月按钮 */
@property (nonatomic, strong) UIButton *lastMouthBtn;  /**< 上一月按钮 */
@property (nonatomic, retain) NSArray *weekDays;  /**< 星期数组 */
@property (nonatomic, assign) BOOL isHeightChange;  /**< 是不是需要加一行 */
@property (nonatomic, strong) UIButton *sureBtn;  /**< 确定按钮 */
@property (nonatomic, strong) UIButton *cancelBtn; /**< 取消按钮 */
@property (nonatomic, assign) NSInteger firstDay; /**< 一个月的第一天 */
@property (nonatomic, assign) NSInteger totalDay; /**< 一个月有多少天 */
@property (nonatomic, assign) NSInteger choisnumber;  /**< 选择的是第几个cell */
@property (nonatomic, assign) NSInteger lastChoisNumber;  /**< 最后选择的cell */
@property (nonatomic, strong) UIImageView *goinHotelImageView; /**< 入住图片 */
@property (nonatomic, strong) UIImageView *gooutHotelImageView;  /**< 离店图片 */
@property (nonatomic, assign) CGPoint imagecenter;
@property (nonatomic, strong) NSDate *dateone;
@property (nonatomic, strong) NSDate *datetwo;

@end

static NSString *identfer = @"kValenderCellKell";

@implementation MHCHChoisTimeView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.frame = CGRectMake(Size_W(0), Size_H(200),Size_W(414), Size_W(414)+Size_H(44));
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.promptChoisTimeLable];
        [self initializeDataSource];
        [self initializeUserInterface];
    }
    return self;
}

-(void)initializeDataSource/**< 初始化数据源 */{
    self.date = [NSDate date];
    self.weekDays = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
    self.lastChoisNumber = -1;
}
-(void)initializeUserInterface/**< 初始化用户界面 */{
    [self addSubview:self.lastMouthBtn];
    [self addSubview:self.nextMouthBtn];
    [self addSubview:self.collectionView];
    [self addlableWithWeek];
    [self addSubview:self.sureBtn];
    [self addSubview:self.cancelBtn];
    [self addSubview:self.goinHotelImageView];
    [self addSubview:self.gooutHotelImageView];
    
}

-(void)addlableWithWeek{
    for (int i = 0; i < 7; i ++) {
        UILabel_Font *lable = [[UILabel_Font alloc]initWithFrame:CGRectMake(Size_W(414)/7.0*i, Size_H(46),Size_W(414-6)/7.0, Size_H(18))];
        lable.backgroundColor = [UIColor orangeColor];
        lable.textAlignment = NSTextAlignmentCenter;
        lable.text = self.weekDays[i];
        [lable setTextColor:[UIColor whiteColor]];
        [self addSubview:lable];
    }
}

-(NSInteger)getTotalDaysInMonthWithDate:(NSDate *)date{
    //得到用户偏好设置
    NSCalendar *calendar = [NSCalendar currentCalendar];
    //获取这个范围
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self.date];
    return range.length;
}



//特定月的第一天是星期几
- (NSInteger)getFristDayOfMonthWithDate:(NSDate *)date {
    //得到用户偏好设置的当前日历
    NSCalendar *calender = [NSCalendar currentCalendar];
    //以星期几作为一个周的第一天
    calender.firstWeekday = 1;//星期天， 2: 周一......
    //通过特定日期来获取日期组件
    NSDateComponents *components = [calender components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:self.date];
    //设置为这个月的第一天
    components.day = 1;
    //根据日期组件得到特定日期(本月的第一天的日期)
    NSDate *firstDay = [calender dateFromComponents:components];
    NSInteger numberOfFirstDay = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDay];
    
    return numberOfFirstDay - 1;//1...7
}

//特定月的第一天是星期几
- (NSInteger)getFristDaOfMonthWithDate:(NSDate *)date{
    //得到当前用户偏好设置的当前日历
    NSCalendar *calender = [NSCalendar currentCalendar];
    //设置以星期几来作为一个周的第一天
    calender.firstWeekday = 1;//1==星期天，1==星期一...7==星期六
    //通过特定日期来获取时期组件
    NSDateComponents *components = [calender components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.date];
    //设置为这个月的第一天
    components.day = 1;
    //根据日期组件得到特定日期（本月第一天的日期）
    NSDate *firstDay = [calender dateFromComponents:components];
    /*< 返回1-7的某一个值 **/
    NSInteger numberOfFirstDay = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDay];
    return numberOfFirstDay - 1;
}


//下一个月

- (NSDate *)nextMonthWithDate:(NSDate *)date {
    
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = 1;
    //得到下一个月
    NSDate *nextDate = [calender dateByAddingComponents:components toDate:date options:0];
    
    return nextDate;
}

//上一个月

- (NSDate *)lastMonthWithDate:(NSDate *)date {
    
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = -1;
    
    NSDate *nextDate = [calender dateByAddingComponents:components toDate:date options:0];
    return nextDate;
}

//下一天

- (NSDate *)nextDayWithDate:(NSDate *)date {
    
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = 1;
    //得到下一个天
    NSDate *nextDate = [calender dateByAddingComponents:components toDate:date options:0];
    
    return nextDate;
}

//上一天

- (NSDate *)lastDayWithDate:(NSDate *)date {
    
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = -1;
    
    NSDate *nextDate = [calender dateByAddingComponents:components toDate:date options:0];
    return nextDate;
}

#pragma mark - 点击事件

-(void)respondsToLastMouthBtn:(UIButton *)sender{
    NSLog(@"上一月");
    self.goinHotelImageView.center = CGPointMake(Size_W(1000), Size_H(1000));
    self.gooutHotelImageView.center = CGPointMake(Size_W(1000), Size_H(1000));
}

- (void)respondsToNextMouthBtn:(UIButton *)sender{
    NSLog(@"下一月");
    self.date = [self lastMonthWithDate:self.date];
    self.goinHotelImageView.center = CGPointMake(Size_W(1000), Size_H(1000));
    self.gooutHotelImageView.center = CGPointMake(Size_W(1000), Size_H(1000));
}

- (void)respondsTosure{
    BOOL isonce = [[NSUserDefaults standardUserDefaults] boolForKey:@"isonce"];
    BOOL isOk = [[NSUserDefaults standardUserDefaults] boolForKey:@"isgoin"];
    NSInteger time1 = [self.dateone timeIntervalSinceNow];
    NSInteger time2 = [self.datetwo timeIntervalSinceNow];
    if (isonce == NO) {
        if (isOk == YES) {
            if (_delegate && [_delegate respondsToSelector:@selector(removeTheCanlenView)]&& time2 >= time1 && time1 && time2) {
                [_delegate removeTheCanlenView];
            }else if(time1 && time2) {
                [Tools showAlertWithMessage:@"请选择正确的时间!"];
            }
        }
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isgoin"];
        self.imagecenter = self.goinHotelImageView.center;
    }else{

        if (_delegate && [_delegate respondsToSelector:@selector(removeTheCanlenView)] && time2>=time1) {
            [_delegate removeTheCanlenView];
        }
    }
    
}

- (void)respondsTocancel{
    if (_delegate && [_delegate respondsToSelector:@selector(removeTheCanlenView)]) {
        [_delegate removeTheCanlenView];
    }
}


#pragma mark -- UICollectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 42;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identfer forIndexPath:indexPath];
    
    [cell.choisImageView removeFromSuperview];
    
        cell.backgroundColor = [UIColor whiteColor];
        cell.daylable.textColor = [UIColor blackColor];
    
        self.firstDay = [self getFristDaOfMonthWithDate:self.date];
        self.totalDay = [self getTotalDaysInMonthWithDate:self.date];
    
        if (indexPath.row < self.firstDay) {
            cell.daylable.text = @"";
        }else if (indexPath.row > self.firstDay + self.totalDay - 1){
            cell.daylable.text = @"";
        }else{
            
            
            cell.backgroundColor = [UIColor lightGrayColor];
            cell.daylable.text = [NSString stringWithFormat:@"%ld",indexPath.row - self.firstDay +1];
            
            cell.daylable.textColor = [UIColor blackColor];
            
            //判断某天是否为周末
            NSCalendar *calender = [NSCalendar currentCalendar];
            NSDateComponents *components = [calender components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:self.date];
            //得到当前cell所对应的日期
            components.day = indexPath.row - self.firstDay +1;
            NSDate *date = [calender dateFromComponents:components];
            BOOL isWeekend = [calender isDateInWeekend:date];
            if (isWeekend) {
                cell.daylable.textColor = [UIColor redColor];
            }
        }
            return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger firstday = [self getFristDaOfMonthWithDate:self.date];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:self.date];
    components.day = indexPath.row - firstday +1;
    NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:components];
    
    BOOL isgoin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isgoin"];
    BOOL isonce = [[NSUserDefaults standardUserDefaults] boolForKey:@"isonce"];
    if (isonce == NO && indexPath.row >= self.firstDay && indexPath.row <= self.totalDay + self.firstDay -1) {
        if (isgoin == NO ) {
            CalendarCollectionViewCell *mycell = (CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:0]];
            self.goinHotelImageView.center = CGPointMake(mycell.center.x, mycell.center.y+Size_H(65));
            if (_delegate && [_delegate respondsToSelector:@selector(selecetedGoinCellWithDate:)]) {
                self.dateone = date;
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isgoin"];
                [_delegate selecetedGoinCellWithDate:date];
            }
        }else if(isgoin == YES && indexPath.row >= self.firstDay && indexPath.row <= self.totalDay + self.firstDay -1){
            CalendarCollectionViewCell *mycell = (CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:0]];
            self.gooutHotelImageView.center = CGPointMake(mycell.center.x, mycell.center.y+Size_H(65));
                self.datetwo = date;
            if (_delegate && [_delegate respondsToSelector:@selector(selecetedGoOutCellWithDate:)]) {
                [_delegate selecetedGoOutCellWithDate:date];
            }
        }
    }else if(isonce == YES && indexPath.row >= self.firstDay && indexPath.row <= self.totalDay + self.firstDay -1){
            CalendarCollectionViewCell *mycell = (CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:0]];
            self.goinHotelImageView.center = CGPointMake(mycell.center.x, mycell.center.y+Size_H(65));


            if (_delegate && [_delegate respondsToSelector:@selector(selecetedoneDayWithDate:)]) {
                    [_delegate selecetedoneDayWithDate:date];
        }
    }else{
        NSLog(@"点击了无效区域");
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM-dd";
    
    NSString *dateString = [formatter stringFromDate:date];
    
    NSLog(@"212=%@",dateString);
    
}



#pragma mark -- Getter & Setter

- (void)setDate:(NSDate *)date {
    _date = date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-dd";
    NSString *dateString = [formatter stringFromDate:date];
    [self.collectionView reloadData];
    NSLog(@"%@",dateString);
    
}

-(UIView *)calendarView{
    if (!_calendarView) {
        _calendarView = [[UIView alloc]initWithFrame:CGRectMake(Size_W(0), Size_H(120),Size_W(414), Size_H(300))];
        _calendarView.backgroundColor = [UIColor whiteColor];
        _calendarView.alpha = 1;
    }
    return _calendarView;
}

- (UILabel_Font *)promptChoisTimeLable{
    if (!_promptChoisTimeLable) {
        _promptChoisTimeLable = [[UILabel_Font alloc]initWithFrame:CGRectMake(Size_W(0), Size_H(0),Size_W(414), Size_H(44))];
        _promptChoisTimeLable.text = @"请选择时间";
        _promptChoisTimeLable.textAlignment = NSTextAlignmentCenter;
        _promptChoisTimeLable.backgroundColor = [UIColor grayColor];
    }
    return _promptChoisTimeLable;
}

- (UIButton *)lastMouthBtn{
    if (!_lastMouthBtn) {
        _lastMouthBtn = [[UIButton alloc]initWithFrame:CGRectMake(Size_W(30), Size_H(2),Size_W(40), Size_H(40))];
        [_lastMouthBtn setImage:[UIImage imageNamed:@"上一月.png"] forState:UIControlStateNormal];
        [_lastMouthBtn addTarget:self action:@selector(respondsToLastMouthBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _lastMouthBtn;
}

- (UIButton *)nextMouthBtn{
    if (!_nextMouthBtn) {
        _nextMouthBtn = [[UIButton alloc]initWithFrame:CGRectMake(Size_W(414-70), Size_H(2),Size_W(40), Size_H(40))];
         [_nextMouthBtn setImage:[UIImage imageNamed:@"下一月.png"] forState:UIControlStateNormal];
        [_nextMouthBtn addTarget:self action:@selector(respondsToNextMouthBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextMouthBtn;
}

-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize = CGSizeMake((CGRectGetWidth(self.bounds)-6)/7,(CGRectGetWidth(self.bounds)-6)/7);
        flowLayout.minimumLineSpacing = 1;
        flowLayout.minimumInteritemSpacing = 1;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, Size_H(65), self.bounds.size.width, Size_W(414-6)/7.0 * 6) collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        /*< 注册原型cell **/
        [_collectionView registerClass:[CalendarCollectionViewCell class] forCellWithReuseIdentifier:identfer];
    }
    return _collectionView;
}

- (UIButton *)sureBtn{
    if (!_sureBtn) {
        _sureBtn = [[UIButton alloc]initWithFrame:CGRectMake(Size_W(30), Size_H(417),Size_W(80), Size_H(40))];
        _sureBtn.backgroundColor = ColorWith(255, 160, 0);
        _sureBtn.layer.cornerRadius = 15;
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_sureBtn addTarget:self action:@selector(respondsTosure) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}

- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(Size_W(414 - 110), Size_H(417),Size_W(80), Size_H(40))];
        _cancelBtn.backgroundColor = ColorWith(255, 160, 0);
        _cancelBtn.layer.cornerRadius = 15;
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(respondsTocancel) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

- (UIImageView *)goinHotelImageView{
    if (!_goinHotelImageView) {
        _goinHotelImageView = [[UIImageView alloc]initWithFrame:CGRectMake(Size_W(100), Size_H(0),Size_W(25), Size_H(25))];
        _goinHotelImageView.center = CGPointMake(Size_W(1000), Size_H(1000));
        _goinHotelImageView.backgroundColor = ColorWith(170, 170, 170);
        _goinHotelImageView.image = [UIImage imageNamed:@"入住"];
        [self addSubview:_goinHotelImageView];
    }
    return _goinHotelImageView;
}

- (UIImageView *)gooutHotelImageView{
    if (!_gooutHotelImageView) {
        _gooutHotelImageView = [[UIImageView alloc]initWithFrame:CGRectMake(Size_W(0), Size_H(0),Size_W(25), Size_H(25))];
        _gooutHotelImageView.center = CGPointMake(Size_W(1000), Size_H(1000));
        _gooutHotelImageView.backgroundColor = ColorWith(170, 170, 170);
        _gooutHotelImageView.image = [UIImage imageNamed:@"离开"];
        [self addSubview:_gooutHotelImageView];
    }
    return _gooutHotelImageView;
}


@end
